<template>
    <div class="publish-body">
        <a-card>
            <a-button style="margin-left: 20px" @click="changeCate">切换类目</a-button>
<!--            <a-button style="margin-left: 20px" @click="testkafk">切换类目</a-button>-->
        </a-card>
        <a-card title="基础信息">
            <a-form-model
                    ref="baseForm"
                    :model="baseForm"
                    :rules="baseFormRules"
                    :label-col="baseFormLabelCol"
                    :wrapper-col="wrapperCol"
            >
                <a-form-model-item label="商品名称" prop="name">
                    <a-input
                            v-model="baseForm.name"
                    />
                </a-form-model-item>
                <a-form-model-item label="子标题" prop="subName">
                    <a-input
                            v-model="baseForm.subName"
                    />
                </a-form-model-item>
                <a-form-model-item label="品牌" prop="brandId">
                    <a-select v-model="baseForm.brandId" placeholder="请选择宝贝品牌" show-search option-filter-prop="children"
                              :filter-option="filterOption"
                    >
                        <a-select-option :value="brand.id" v-for="brand in cateBrandData">
                            {{brand.name}}
                        </a-select-option>
                    </a-select>
                    <span>未找到需要的品牌， <a href="/apply-brand">点击申请</a></span>
                </a-form-model-item>

                <a-form-model-item label="是否立即上架" prop="onSell">
                    <a-radio-group v-model="baseForm.onSell">
                        <a-radio value="1">
                            上架
                        </a-radio>
                        <a-radio value="0">
                            存至仓库
                        </a-radio>
                    </a-radio-group>
                </a-form-model-item>
                <a-form-model-item label="关键词" prop="keywords">
                    <a-input
                            v-model="baseForm.keywords"
                    />
                </a-form-model-item>

                <a-form-model-item label="配送快递" prop="expressId">
                    <a-select v-model="baseForm.expressId" placeholder="请选择快递配送方">
                        <a-select-option value="1">
                            中通快递
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="店内排序" prop="order">
                    <a-input-number
                            :min="1"
                            v-model="baseForm.order"
                    />
                </a-form-model-item>
                
                <a-form-model-item label="包装清单" prop="packingList">
                    <a-textarea
                            v-model="goods.goodsDetail.packingList"
                    />
                </a-form-model-item>

            </a-form-model>

        </a-card>
        <a-card title="类目属性">
            <form-create style="padding:0px 50px 50px 50px" @on-submit="onSubmit" ref="leiform" v-model="commonFormApi"
                         :rule="commonRule"
                         :option="option"></form-create>

        </a-card>
        <a-card title="销售属性">
            <span v-if="goodsId" style="color: red;margin-left: 200px">移除属性事件中修改属性值有官方BUG，数据值修改了，但是UI展示无效，新版本会修复，这里前端未控制，只在后端控制。</span>
            <form-create style="padding:0px 50px 50px 50px" ref="sellform" v-model="sellFormApi"
                         :rule="sellRule"
                         :option="sellFormOption" @on-submit="sortSellSpec"></form-create>

            <div v-if="data&&data.length>0">
                <a-checkbox @change="yikoujia">一口价</a-checkbox>
                <a-input-number :min="0" v-model="yikouPojo.price"
                                @change="value => yikouPrice(value)"></a-input-number>
            </div>
            <a-table v-if="data.length>0" :pagination="false" :columns="columns" :data-source="data"
                     :scroll="{ x: 700, y: 600 }">
                <div slot="pictures" slot-scope="text,record,recordIndex">
                    <span v-for="(pic,index) in record.pictureList">
                        <img :src="pic" style="width: 100px;height: 100px;margin: 10px"/>
                        <a-button icon="minus" @click="removePic(index,recordIndex)"></a-button>
                    </span>


                </div>
                <span slot="giveIntegral" slot-scope="text,record,recordIndex">
                    {{record.giveIntegral?'是':'否'}}
                </span>

                <template
                        v-for="col in ['price', 'stock']"
                        :slot="col"
                        slot-scope="text, record, index"
                >
                    <div :key="col">
                        <a-input-number
                                :min="0"
                                v-if="record.editable"
                                style="margin: -5px 0"
                                :value="text"
                                @change="e => handleCellEditChange(e, index, col)"
                        />
                        <template v-else>
                            {{ text }}
                        </template>
                    </div>
                </template>
                <template slot="action" slot-scope="text, record, index">
                    <!--选中sku-->
                    <a-checkbox :checked="record.checked" @change="selectSku(index,record)">
                    </a-checkbox>
                    <a-divider type="vertical"/>

                    <!--保存/取消单元格-->
                    <span v-if="record.checked&&record.editable">
                          <a @click="() => saveCellSpec(index,record)">保存</a>
                            <a-divider type="vertical"></a-divider>

                            <a @click="() => cancelCellEdit(index)">取消</a>

                    </span>
                    <!--编辑单元格-->
                    <span v-if="record.checked&&!record.editable">
                      <a :disabled="editingKey !== ''" @click="() => edit(index)"><a-icon type="edit"/></a>
                    </span>
                    <a-divider type="vertical"/>
                    <span v-if="record.checked">
                            <hidden-up-load style="height: 50px" ref="hiddenUpLoad" @getImageUrl="getImageUrl"
                                            :index="index">
                                </hidden-up-load>
                    </span>
                    <a-divider type="vertical"/>

                    <span v-if="record.checked&&record.pictureList.length>0">
                           <a-select
                                   label-in-value
                                   placeholder="应用相同图片"
                                   style="width: 150px"
                                   @change="value=>applyPicturesToSpec(value,record)"
                           >
                            <a-select-option v-for="col in specColumn" :value="col.dataIndex">
                              {{col.title}}
                            </a-select-option>

                          </a-select>
                    </span>
                    <a-checkbox v-if="record.checked" :checked="record.giveIntegral"
                                @change="target=>giveIntegral(target,{index,record})">
                        赠送积分
                    </a-checkbox>


                </template>
            </a-table>
        </a-card>
        <a-card title="商品详情">
            <my-quill-editor :content="goods.goodsDetail.content" @getQuillContent="getQuillContent"
                             @refreshRemoveImages="refreshRemoveImages"
                             :toRemoveIds="goods.removeImages" field="content"></my-quill-editor>
        </a-card>
        <a-card title="售后保障">
            <my-quill-editor @getQuillContent="getQuillContent" @refreshRemoveImages="refreshRemoveImages"
                             :content="goods.goodsDetail.afterSaleProtection" :toRemoveIds="goods.removeImages"
                             field="afterSaleProtection"></my-quill-editor>
        </a-card>
        <div class="bottom-commit">
            <a-button class="bottom-btn" type="primary" @click="onSubmit">提交
            </a-button>
        </div>

        <!--  <a-upload
                  ref="hiddenUpLoad"
                  style="display: none"
                  name="avatar"
                  class="avatar-uploader"
                  :show-upload-list="false"

          >
              <div class="ant-upload-text">
                  Upload
              </div>
          </a-upload>-->
    </div>
</template>

<script>
    import formCreate from "@form-create/ant-design-vue";
    import specApi from "../../../../api/goods/SpecApi";
    import MyQuillEditor from "../../../../components/MyQuillEditor";
    import {diskaer} from "../../../../utils/dikaer";
    import {filterRepeat} from "../../../../utils/arrayUtil";
    import UpLoad from "../../../../components/upload/UpLoad";
    import HiddenUpLoad from "../../../../components/upload/HiddenUpLoad";
    import brandApi from "../../../../api/goods/brandApi";
    import goodsApi from "../../../../api/goods/goodsApi";
    import {getJsonUrlParam} from "../../../../utils/urlUtils";

    const defaultColumns = [


        {
            title: '单价',
            dataIndex: 'price',
            width: 100,
            scopedSlots: {customRender: 'price'},

        },
        {
            title: '库存',
            dataIndex: 'stock',
            width: 100,
            scopedSlots: {customRender: 'stock'},

        },
        {
            title: '赠送积分',
            dataIndex: 'integral',
            width: 100,
            scopedSlots: {customRender: 'integral'},

        },
        {
            title: '是否赠送积分',
            dataIndex: 'giveIntegral',
            width: 100,
            scopedSlots: {customRender: 'giveIntegral'},

        },
        {
            title: '图片',
            dataIndex: 'pictureList',
            width: 500,
            scopedSlots: {customRender: "pictures"}
        },
        {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 400,
            scopedSlots: {customRender: 'action'},
        }
    ]

    /**
     * 获取销售规格笛卡尔积 表格columns定义
     */
    function getColumns(skus) {
        let columns = []
        columns.push({
            title: "序号",
            customRender: (text, record, index) =>
                index,
            width: 50
        })
        for (let i = 0; i < skus.length; i++) {
            let column = {}
            let skip = 1; //合并的行数间隔 第i列的合并行数为 第 i+1 到 第skus.length 列 数据个数的阶乘
            for (let j = i + 1; j < skus.length; j++) {
                skip *= skus[j].data.length
            }
            column.title = skus[i].title;
            column.dataIndex = skus[i].dataIndex;
            column.width = 100
            column.customRender = (value, row, index) => {
                const obj = {
                    children: value,
                    attrs: {},
                };
                //第0行和第 index%skip===0的行要合并skip行
                if (index === 0 || index % skip === 0) {
                    obj.attrs.rowSpan = skip;
                } else {
                    obj.attrs.rowSpan = 0
                }

                return obj;
            }
            columns.push(column)
        }
        defaultColumns.forEach(item => columns.push(item))
        return columns;
    }

    export default {
        name: "publishForm",
        components: {HiddenUpLoad, UpLoad, MyQuillEditor},
        data() {
            return {
                goodsId: null,//有值说明是编辑
                rawSkuList: [],//修改时需要回显的sku数据
                rawSkuParam: [],//修改时当前商品已有的skuParam
                beginFetch: false, //删除sku属性的事件时需判断是否为第一次加载赋值触发

                editingKey: '',
                columns: [],
                data: [],
                //实例对象
                sellFormApi: {},
                commonFormApi: {},
                commonRule: [],//类目属性规格
                sellRule: [],//销售属性规格
                //组件参数配置
                option: {
                    //表单提交事件
                    submitBtn: false,
                    resetBtn: false,
                    global: {
                        '*': {
                            col: {
                                span: 12,
                            }
                        },
                    }
                },
                sellFormOption: {
                    submitBtn: {
                        //按钮类型，可选值为primary、ghost、dashed、text、info、success、warning、error或者不设置
                        type: "link",
                        //按钮大小，可选值为large、small、default或者不设置
                        size: "large",
                        icon: "",
                        innerText: "开始排序",

                    },
                    global: {
                        '*': {
                            col: {
                                span: 23,
                                offset: 1
                            }
                        },
                    }
                },

                //基础信息表单
                baseFormLabelCol: {span: 4},
                wrapperCol: {span: 14},
                other: '',
                baseForm: {
                    name: '',
                    brandId: undefined,
                    shopId: null,
                    subName: '',
                    keywords: '',
                    order: null,
                    onSell: '1',
                    expressId: "1",
                    content: "",
                    packingList: ""
                },
                cateBrandData: [],//当前分类下的所有品牌
                baseFormRules: {
                    name: [
                        {required: true, message: '请输入宝贝名称', trigger: 'blur'},
                    ],
                    subName: [
                        {required: true, message: '请输入副标题', trigger: 'blur'},
                    ],
                    keywords: [
                        {required: true, message: '请输入宝贝关键词', trigger: 'blur'},
                    ],
                    order: [
                        {required: true, message: '请输入店内排序', trigger: 'blur'},

                    ]
                },
                goods: {
                    goodsDetail: {},
                    skus: [],
                    goods: {},
                    removeImages: []
                },
                filterColumnNames: ["price", "stock", "integral", "pictureList", "checked", "giveIntegral", "id"], //封装SKU的规格时时需要把这些列字段去掉
                specColumn: [], //应用图片到相同规格时选择的规格,

                yikouPojo: {
                    isYikouJia: false,//是否一口价 如果一口价则不需要填写sku价格
                    price: 0.00,
                }

            }
        },
        created() {
            this.loadDynamicForm()
            this.cateBrand()

        },
        methods: {
            /**
             *  移除规格项中的图片
             */
            removePic(index, recordIndex) {
                let newData = [...this.data];
                let target = newData[recordIndex];
                if (target) {
                    this.goods.removeImages.push(target.pictureList[index])
                    target.pictureList.splice(index, 1);
                    this.data = newData;

                }
            },
            /**
             *  将当前行的图片应用到指定规格项的相同值的sku图片中
             *  @param value :{key:规格id,label:列名}
             *  @param recordData :{}
             */
            applyPicturesToSpec(value, record) {
                if (record.pictureList && record.pictureList.length > 0) {
                    let spec = value.key
                    //选中的规格项在当前行的值
                    let selectSpecValue = record[spec]
                    if (selectSpecValue) {
                        const newData = [...this.data];
                        newData.forEach(data => {
                            if (data[spec] === selectSpecValue) {
                                data.pictureList = record.pictureList;
                            }
                        })
                        if (newData) {
                            this.data = newData;
                        }
                    }
                }


            },
            /**
             * 初始化销售规格（应用图片到指定规格属性值用到）
             */
            initSkuIdNameColumn() {
                let columns = [...this.columns];
                let specColumn = columns.filter(column => column.dataIndex && !this.filterColumnNames.includes(column.dataIndex))
                console.log(specColumn)
                this.specColumn = specColumn;
            },
            filterOption(input, option) {

                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            cateBrand() {
                if (this.goods.goods.cid3) {
                    brandApi.cateBrand(this.goods.goods.cid3).then(Resp => {
                        if (Resp.data.flag) {
                            this.cateBrandData = Resp.data.data;
                        }
                    })

                }
            },
            /**
             *  富文本每次改变后刷新已经上传但被移除的图片
             */
            refreshRemoveImages(removeIds) {
                console.log(removeIds)
                if (removeIds && removeIds.length > 0) {
                    removeIds.forEach(id => this.goods.removeImages.push(id))
                }
            },
            /**
             * 富文本编辑器改变的回调
             */
            getQuillContent(content, field) {
                if (field === "afterSaleProtection") {
                    this.goods.goodsDetail.afterSaleProtection = content;
                } else if (field === "content") {
                    this.goods.goodsDetail.content = content;
                }
            },
            /**
             *  上传图片后返回的图片地址
             */
            getImageUrl(imageUrl, index) {
                // console.log(imageUrl)
                // console.log(index)
                const newData = [...this.data];
                const target = newData[index]
                if (target) {
                    console.log(newData)
                    target.pictureList.push(imageUrl)
                    this.data = newData;
                }
            },
            /**
             *  选中sku
             */
            selectSku(index, record) {
                const newData = [...this.data];
                console.log(newData)
                const target = newData[index]
                if (target) {
                    if (record.checked && this.goodsId && this.rawSkuList.length > 0) {
                        //修改商品：不可以取消已有的sku项
                        console.log(target)
                        let rawSkuList = this.rawSkuList;
                        console.log(rawSkuList)
                        let flag = true;
                        rawSkuList.forEach(sku => {
                            if (sku.id === target.id) {
                                flag = false;
                                this.$notification['warning']({
                                    message: '无法删除原始规格项',
                                    description:
                                        '已发布的商品禁止移除已发布规格项，只能修改价格和库存，可在商品中心清空库存；如要更改SKU详细信息，则需要先下架该商品，重新上架相关的商品',
                                    duration: 6,

                                });
                            }
                        })
                        if (!flag) {
                            return;
                        }
                    }
                    Object.assign(target, record);
                    target.checked = !record.checked;
                    this.data = newData;
                }
            },
            /**
             *  一口价值
             */
            yikouPrice(value) {
                const newData = [...this.data];
                newData.forEach(data => {
                    data.price = value;
                    if (data.giveIntegral) {
                        data.integral = data.price / 2;
                    }
                })
                this.data = newData;
            },
            /**
             *  一口价选择
             */
            yikoujia({target}) {
                this.yikouPojo.isYikouJia = target.checked;
                this.yikouPojo.price = 0
            },
            /**
             *  开启sku赠送积分
             */
            giveIntegral(value, {index, record}) {
                const newData = [...this.data];
                const target = newData[index]
                if (target) {
                    Object.assign(target, record);
                    target.giveIntegral = value.target.checked;
                    if (target.giveIntegral) {
                        if (record.price) {
                            target.integral = record.price / 2;
                        }
                    } else {
                        target.integral = 0.00;
                    }
                    console.log(newData)
                    this.data = newData;
                }
            },
            /**
             * 保存笛卡尔表格单元格编辑项
             */
            saveCellSpec(index, record) {
                const newData = [...this.data];
                const target = newData[index]
                if (target) {
                    delete target.editable;
                    Object.assign(target, record);
                    // this.goods.skus[index] = target;
                    // console.log(this.goods)
                    this.data = newData;
                }
                this.editingKey = '';
            },
            /**
             * 取消笛卡尔表格单元格编辑
             */
            cancelCellEdit(index) {
                const newData = [...this.data];
                const target = newData[index]
                this.editingKey = '';
                if (target) {
                    delete target.editable;
                    this.data = newData;
                }
            },
            edit(index) {
                const newData = [...this.data];
                const target = newData[index]
                this.editingKey = index;
                if (target) {
                    console.log(target)
                    target.editable = true;
                    this.data = newData;
                }
            },
            /**
             *  表格单元格编辑改变时的回调
             */
            handleCellEditChange(value, index, column) {
                const newData = [...this.data];
                const target = newData[index]
                if (target) {
                    if (column === "price") {
                        target[column] = value;

                        if (target.giveIntegral) {
                            target.integral = value / 2;
                        }
                    } else {
                        //修改库存
                        if (this.goodsId && this.rawSkuList.length > 0) {
                            let rawSkuList = this.rawSkuList;
                            let flag = true;
                            console.log("aaaaaaaaaaaaaaaaaaa")
                            rawSkuList.forEach(sku => {
                                if (sku.id === target.id && sku.stock > value) {
                                    flag = false;
                                    this.$message.warning("原始规格项的库存只能增加不能减少", 1)
                                }
                            })
                            if (!flag) {
                                return;
                            }
                        }
                        target[column] = value;


                    }
                    this.data = newData;
                }

            },

            loadDynamicForm() {
                let urlParamObj = getJsonUrlParam()
                if (urlParamObj && urlParamObj.cate1 && urlParamObj.cate2 && urlParamObj.cate3) {
                    this.goods.goods.cid2 = urlParamObj.cate2.id
                    this.goods.goods.cid1 = urlParamObj.cate1.id
                    this.goods.goods.cid3 = urlParamObj.cate3.id
                    console.log(this.goods.goods.cid2)
                    console.log(this.goods.goods.cid1)
                    console.log(this.goods.goods.cid3)
                    if (urlParamObj.goods) {
                        this.goodsId = urlParamObj.goods.id
                    }
                    specApi.loadDynamicForm(urlParamObj.cate3.id).then(resp => {
                            if (resp.data.flag) {
                                this.commonRule = resp.data.data.commonSpecs;
                                let sellSpecs = resp.data.data.sellSpecs
                                sellSpecs.forEach(item => {
                                    item.value = [];
                                    item.on = {
                                        //TODO 目前remove事件中修改group的value值有官方bug，UI不会被更新但是获取group的value已经变化了 只有删除最后一个条目的时候才有效
                                        //TODO ISSUE 地址：https://github.com/xaboy/form-create/issues/222 作者会在下个版本修复 大概还会支持group禁止移除功能
                                        remove: (e) => {
                                            if (this.rawSkuParam.length <= 0) {
                                                return;
                                            }
                                            console.log(e)
                                            console.log(item)
                                            let delKey = item.field
                                            //未被删除的值

                                            //规格项的原始所有值
                                            let targetParam = this.rawSkuParam[delKey]
                                            console.log(targetParam)

                                            if (targetParam && targetParam.length > 0) {
                                                //已经是删除后的了
                                                let sellRule = [...this.sellRule]
                                                let target = sellRule.find(rule => rule.field === delKey)
                                                if (target) {
                                                    let sellSpecValue = []

                                                    targetParam.forEach(param => {
                                                        let val = {}

                                                        val[delKey] = param
                                                        console.log(param)
                                                        console.log(val)
                                                        sellSpecValue.push(val)
                                                    })
                                                    target.value = sellSpecValue
                                                    Object.assign(this.sellRule, sellRule)
                                                }


                                            }


                                        }
                                    }
                                })
                                this.sellRule = sellSpecs;
                                if (this.goodsId) {
                                    this.fetchGoodsInfo()
                                }
                                this.$nextTick(() => {
                                    this.beginFetch = false;
                                })

                            }
                        }
                    )

                }


            },
            /**
             * 获取待编辑商品信息
             */
            fetchGoodsInfo() {
                this.beginFetch = true;
                goodsApi.goodsEditInfo(this.goodsId).then(resp => {
                    if (resp.data.flag) {
                        let goodsInfoData = resp.data.data;
                        let goods = goodsInfoData.goods;
                        let goodsDetail = goodsInfoData.goodsDetail
                        let skus = goodsInfoData.skus

                        console.log(goodsInfoData)
                        console.log(goods)
                        console.log(goodsDetail)
                        this.baseForm = {
                            name: goods.name,
                            brandId: goods.brandId + '',
                            subName: goods.subName,
                            shopId: goods.shopId,
                            keywords: goods.keywords,
                            order: goods.order,
                            onSell: goods.onSell + '',
                            expressId: goods.expressId + '',
                            content: goods.content,
                        }
                        this.rawSkuList = skus
                        this.rawSkuParam = JSON.parse(goodsDetail.skuParam);
                        this.goods.goodsDetail.packingList = goodsDetail.packingList
                        this.goods.goodsDetail.afterSaleProtection = goodsDetail.afterSaleProtection
                        this.goods.goodsDetail.content = goodsDetail.content
                        if (this.commonRule && this.commonRule.length > 0) {
                            let commonSpec = JSON.parse(goodsDetail.commonParam);
                            this.commonRule.forEach(commonRule => {
                                commonRule.value = commonSpec[commonRule.field]

                            })
                        }
                        if (this.sellRule && this.sellRule.length > 0) {
                            let skuParam = JSON.parse(goodsDetail.skuParam);
                            this.sellRule.forEach(sellSpec => {
                                if (sellSpec.props.rules.length > 0) {
                                    //当前动态添加的表单一个props.rules中只有一个表单项
                                    let fieldName = sellSpec.props.rules[0].field;
                                    let paramList = skuParam[fieldName];
                                    if (paramList && paramList.length > 0) {
                                        paramList.forEach(param => {
                                            let val = {}
                                            val[fieldName] = param
                                            sellSpec.value.push(val)
                                            console.log(sellSpec.value)
                                        })
                                    }
                                }
                            })
                            console.log(this.sellRule)
                        }
                        this.sortSellSpec()
                    }
                })
                // this.beginFetch=false;
            }
            ,
            resetForm() {
                this.$refs.ruleForm.resetFields();
            }
            ,
            testkafk() {
                goodsApi.testkafk("1346286625394057217").then(resp => {
                })
            }

            ,
            onSubmit() {
                console.log(this.goods)
                console.log(this.baseForm)

                //基础信息
                this.$refs.baseForm.validate(valid => {
                    if (valid) {
                        Object.assign(this.goods.goods, this.baseForm)
                        //通用规格
                        this.commonFormApi.submit((formData, $f) => {
                            this.goods.goodsDetail.commonParam = JSON.stringify(formData);
                        })
                        if (!this.data || this.data.length <= 0) {
                            this.$message.warning("请填写销售规格并排序");
                            return;
                        }

                        let newSkuData = [...this.data].filter(item => item.checked)
                        if (newSkuData.length <= 0) {
                            this.$message.warning("请至少选择一个销售规格项");
                            return;

                        }
                        let valid = false;
                        newSkuData.forEach(item => {
                            if (item.price && item.stock && item.integral>=0 && item.pictureList) {
                                if (item.pictureList.length <= 0) {
                                    this.$message.warning("请上传选中规格的宝贝图片")
                                } else {
                                    valid = true;
                                }
                            } else {
                                if (!item.price && this.yikouPojo.isYikouJia) {
                                    this.$message.warning("请填写宝贝价格(一口价)")
                                } else {
                                    this.$message.warning("请将宝贝销售信息补充完整")

                                }
                            }
                        })

                        if (valid) {
                            let skus = this.skuTableData2Sku(newSkuData)

                            if (skus) {
                                this.goods.skus = skus
                                if (this.goodsId) {
                                    //修改
                                    this.goods.goods.id = this.goodsId
                                    console.log(this.goods)
                                    goodsApi.update(this.goods).then(resp => {
                                        if (resp.data.flag) {

                                            this.$message.success("修改成功", 1);
                                            this.$router.push("/cell-center/goods_center")

                                        }
                                    })
                                } else {
                                    goodsApi.publish(this.goods).then(resp => {
                                        if (resp.data.flag) {
                                            window.location.reload()
                                            this.$message.success("发布成功", 1);

                                        }
                                    })
                                }

                            }
                        }

                    } else {
                        return false;
                    }
                });
            }
            ,
            skuTableData2Sku(skuData) {
                let skus = []
                for (let i = 0; i < skuData.length; i++) {
                    let data = skuData[i]
                    let sku = {}


                    if (data.pictureList && data.pictureList.length > 0) {
                        sku.pictureList = data.pictureList;
                    }
                    if (!this.baseForm.name || this.baseForm.name === '') {
                        this.$message.warning("请先填写宝贝基本信息")
                        return;
                    }
                    sku.name = this.baseForm.name + ' '
                    sku.price = data.price;
                    sku.id = data.id ? data.id : null;
                    sku.stock = data.stock;
                    sku.integral = data.integral && data.integral > 0 ? data.integral : 0;
                    sku.giveIntegral = sku.integral > 0 ? true : false;
                    sku.showIndex = 0;
                    let spec = {}
                    for (let key in data) {
                        //只保留销售规格
                        if (!this.filterColumnNames.includes(key)) {
                            spec[key] = data[key]
                        }
                    }
                    sku.spec = JSON.stringify(spec)
                    let specIndexes = '';
                    let skuParams = JSON.parse(this.goods.goodsDetail.skuParam)

                    let jsonSpec = JSON.parse(sku.spec)
                    for (let key in jsonSpec) {
                        console.log("wwwwwwwwwwww")
                        specIndexes += skuParams[key].indexOf(jsonSpec[key]) + '_'
                        sku.name += skuParams[key] + ' '
                    }
                    sku.specIndexes = specIndexes.substring(0, specIndexes.length - 1);
                    skus.push(sku)
                }
                return skus;
            }
            ,
            /**
             * 对已填写销售规格进行笛卡尔组合 生成表格
             */
            sortSellSpec() {
                this.sellFormApi.submit((formData, $f) => {
                    //保存sku参数
                    let skuParam = {}
                    /**
                     * formData格式：[{id:[{id:value},{id:value}]}] 只要id和value
                     */
                    for (let key in formData) {
                        let params = []
                        for (let id in formData[key]) {
                            //id为数组序号
                            params.push(formData[key][id][key])
                        }
                        skuParam[key] = params
                    }
                    console.log(skuParam)
                    console.log("..........")
                    this.goods.goodsDetail.skuParam = JSON.stringify(skuParam);
                    //原始规则 用于获取字段名
                    let rules = JSON.parse($f.toJson());
                    let skus = []
                    let index = 0;
                    Object.keys(formData).map((key) => {

                        if (key === rules[index].field) {
                            let sku = {}
                            sku.title = rules[index].title
                            sku.dataIndex = key
                            //去除规格重复值
                            sku.data = filterRepeat(formData[key], key)
                            skus.push(sku)

                        }
                        index++;
                    });
                    console.log(skus)
                    console.log("skus")

                    let columns = getColumns(skus);
                    this.columns = columns;
                    let skuDatas = []
                    skus.forEach(sku => skuDatas.push(sku.data))
                    //获取笛卡尔积后的数据集合
                    let dikaerData = diskaer(skuDatas)
                    console.log(dikaerData)

                    dikaerData.forEach(item => {
                        if (this.goodsId && this.rawSkuList.length > 0) {

                            let same = true;

                            //如果是修改的话，需要回显sku数据
                            for (let i = 0; i < this.rawSkuList.length; i++) {
                                same = true;
                                let rawSku = this.rawSkuList[i];
                                let rawSkuSpec = JSON.parse(rawSku.spec);
                                for (let key in item) {
                                    if (rawSkuSpec[key] !== item[key]) {
                                        same = false;
                                    }
                                }
                                if (same === true) {
                                    item.id = rawSku.id
                                    item.price = rawSku.price
                                    item.stock = rawSku.stock
                                    item.integral = rawSku.integral
                                    item.giveIntegral = rawSku.giveIntegral
                                    item.checked = true;
                                    item.pictureList = JSON.parse(rawSku.pictures)
                                    break;
                                }
                                continue;

                            }
                            if (same === false) {
                                item.pictureList = [];
                                item.checked = false;
                                item.giveIntegral = false;
                            }

                        } else {
                            item.pictureList = [];
                            item.checked = false;
                            item.giveIntegral = false;
                        }

                    })
                    this.data = dikaerData
                })
                this.initSkuIdNameColumn()

            }
            ,
            test(record) {
                console.log(record)
            }
            ,
            changeCate() {
                let that = this;
                this.$confirm({
                    title: '确定切换类目吗?',
                    content: '切换类目后系统将不会保存现有的表单项',
                    onOk() {
                        that.$router.push("/cate-choose")
                    },
                    okText: "确定",
                    onCancel() {
                    },
                    cancelText: "取消"
                });
            }
        }
    }
</script>

<style>

    .bottom-commit {
        position: fixed;
         height: 72px;
        width: 100%;
        bottom: 0px;
        text-align: center;
        border-top: #4A77FF solid 2px;
        background: white;
    }

    .bottom-btn {
        height: 40px;
        margin: 16px;
        width: 160px;
        border: #0085D7 solid 1px;
    }


</style>